import PageComponent from '@components/pageComponent'
import style from './index.module.less'
import { UnorderedListOutline, CloseCircleOutline, AddCircleOutline } from 'antd-mobile-icons'
import { Button, ErrorBlock, Popup, Skeleton, Space } from 'antd-mobile'
import { useEffect, useMemo, useRef, useState } from 'react'
import { getListRequest, getDetailRequest, sendRequest } from './ajax'
import { awaitWrap, formatDate } from '@src/assets/js/tool'
import classNames from 'classnames'
import robot from '@imgs/robot.png'
import $ from 'jquery'

async function initList (setList, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest())
  setLoading(false)
  if (e === null && d !== null) {
    setList(d)
  }
}

async function getDetail (ref, id, setDetail, setLoading, setAnswering, setContent) {
  setLoading(true)
  const [e, d] = await awaitWrap(getDetailRequest(id))
  setLoading(false)
  setAnswering(false)
  setContent('')
  if (e === null && d !== null) {
    setDetail(d)
    setTimeout(() => {
      const c = ref.current
      if (c !== null) {
        $(c).animate({ scrollTop: c.scrollHeight })
      }
    }, 0)
  }
}

async function send (ref, lastid, title, setLoading, setAnswering, setCurrentId, setCurrentTitle, setListVersion, setVersion) {
  setLoading(true)
  setAnswering(true)
  setTimeout(() => {
    const c = ref.current
    if (c !== null) {
      $(c).animate({ scrollTop: c.scrollHeight })
    }
  }, 0)
  const [e, d] = await awaitWrap(sendRequest(title, lastid))
  setLoading(false)
  if (e === null && d !== null) {
    if (lastid === '') {
      setCurrentId(d.sessionid)
      setCurrentTitle(title)
    } else {
      setVersion(Date.now())
    }
    setListVersion(Date.now())
  }
}

function dealAnswer (t) {
  const s = t.replace(/\n/g, '<br />').replace(/\\n/g, '<br />')
  const l = s.split('<br />').filter(li => li)
  return (
    <>
      {l.map((li, i) => {
        return (
          <p key={i}>{li}</p>
        )
      })}
    </>
  )
}

function Main () {
  const ref = useRef(null)
  const [visible, setVisible] = useState(false)
  const [list, setList] = useState([])
  const [listLoading, setListLoading] = useState(false)
  const [currentId, setCurrentId] = useState('')
  const [currentTitle, setCurrentTitle] = useState('')
  const [detail, setDetail] = useState(null)
  const [detailLoading, setDetailLoading] = useState(false)
  const [content, setContent] = useState('')
  const [sending, setSending] = useState(false)
  const [answering, setAnswering] = useState(false)
  const [listVersion, setListVersion] = useState(Date.now())
  const [detailVersion, setDetailVersion] = useState(Date.now())
  const message = useMemo(() => {
    if (detail) {
      return detail.message
    }
    return []
  }, [detail])
   const lastid = useMemo(() => {
    if (message.length > 0) {
      return message[message.length - 1].sessionid
    }
    return ''
  }, [message])
  useEffect(() => {
    initList(setList, setListLoading)
  }, [listVersion])
  useEffect(() => {
    if (currentId) {
      getDetail(ref, currentId, setDetail, setDetailLoading, setAnswering, setContent)
    }
  }, [currentId, detailVersion])
  return (
    <PageComponent title={currentTitle ? <span className={style.title}>{decodeURIComponent(currentTitle)}</span> : '新建聊天'} right={(
      <Space style={{ '--gap': '.6rem' }}>
        <a className={style['list-btn']} onClick={() => { setCurrentId(''); setCurrentTitle(''); setDetail(null) }}><AddCircleOutline /></a>
        <a className={style['list-btn']} onClick={() => setVisible(true)}><UnorderedListOutline /></a>
      </Space>
    )}>
      <div className={style.container}>
        <div className={style['message-list']}>
          <div className={style['message-list-inner']} ref={ref}>
            {
              detailLoading && !answering && message.length === 0 && (
                <div className={style.loading}>
                  <Skeleton.Paragraph lineCount={5} animated />
                </div>
              )
            }
            {
              !detailLoading && message.length === 0 && !answering && (
                <div>
                  <ErrorBlock status='empty' title='暂无数据' description={false} />
                </div>
              )
            }
            <div className={style.message}>
              {
                message.map((li, i) => {
                  return (
                    <div key={i}>
                      <div className={style.item}>
                        <div className={style['item-tag']}>我</div>
                        <div className={style['item-content']}>{decodeURIComponent(li.title)}</div>
                      </div>
                      <div className={style.item}>
                        <div className={style['item-icon']}><img src={robot} /></div>
                        <div className={style['item-content']}>
                          {dealAnswer(li.answer)}
                        </div>
                      </div>
                    </div>
                  )
                })
              }
              {
                answering && (
                  <div>
                    <div className={style.item}>
                      <div className={style['item-tag']}>我</div>
                      <div className={style['item-content']}>{content}</div>
                    </div>
                    <div className={style.item}>
                      <div className={style['item-icon']}><img src={robot} /></div>
                      <div className={style['item-content']}>
                        <div className={style['answer-dot']} />
                      </div>
                    </div>
                  </div>
                )
              }
            </div>
          </div>
        </div>
        <div className={style['input-block']}>
          <div className={style.input}>
            <input placeholder='请输入' value={content} disabled={sending} onInput={e => setContent(e.target.value)} />
            <Button className={style.send} color='primary' loading={sending} onClick={() => {
              send(ref, lastid, content, setSending, setAnswering, setCurrentId, setCurrentTitle, setListVersion, setDetailVersion)
            }}>发送</Button>
          </div>
        </div>
        <Popup visible={visible} position='right' bodyClassName={style.popup} onMaskClick={() => { setVisible(false) }}>
          <div className={style.history}>
            <div className={style['history-header']}>
              <span>历史话题</span>
              <a className={style.close} onClick={() => setVisible(false)}><CloseCircleOutline /></a>
            </div>
            <div className={style['history-content']}>
              <div className={style['history-content-inner']}>
                {
                  listLoading && (
                    <div className={style.loading}>
                      <Skeleton.Paragraph lineCount={5} animated />
                    </div>
                  )
                }
                {
                  !listLoading && list.length === 0 && (
                    <div>
                      <ErrorBlock status='empty' title='暂无数据' description={false} />
                    </div>
                  )
                }
                {
                  list.map((li, i) => {
                    return (
                      <a key={i} className={classNames(style['history-item'], { [style.active]: li.id === currentId })} onClick={() => {
                        setCurrentId(li.id)
                        setCurrentTitle(li.title)
                        setVisible(false)
                        setDetail(null)
                      }}>
                        <div className={style['history-item-title']}>{decodeURIComponent(li.title)}</div>
                        <div className={style['history-item-date']}>{formatDate(li.update_datetime)}</div>
                      </a>
                    )
                  })
                }
              </div>
            </div>
          </div>
        </Popup>
      </div>
    </PageComponent>
  )
}

export default Main
